import React, {useEffect, useState} from "react";
import {useParams} from "react-router-dom/cjs/react-router-dom";
import './index.scss'
import Axios from "../../utils/Axios";
import del from '../../assets/images/delUser.png'

import {
  Button,
  DatePicker,
  Empty,
  Input,
  List,
  message,
  Modal,
  Popconfirm,
  TimePicker
} from "antd";
import TextArea from "antd/es/input/TextArea";
import AttendanceInfo from "../../components/AttendanceInfo";

const {Search} = Input;

function AttPage() {
  const params = useParams()
  const [users, setUsers] = useState([])
  const [searchUser, setSearchUser] = useState([])
  const [groupInfo, setGroupInfo] = useState({})
  const [attdances, setAttdances] = useState([])
  const [mustRender, setMustRender] = useState(0)
  const [attInfoItem, setAttInfoItem] = useState({})

  const [isModalVisible, setIsModalVisible] = useState(false)
  const [addAttVisible, setAddAttvisible] = useState(false)
  const [attInfoVisible, setAttInfoVisible] = useState(false)

  const onSearch = async value => {
    const res = await Axios.post(`/admin/searchUsers/${value}`)
    if (res.data.code === 200) {
      setSearchUser(res.data.data)
    }
  };
  const addUserToGroup = async (id) => {
    const res = await Axios.post(`/admin/groupUser/${params.id}/${id}`)
    if (res.data.code === 200) {
      message.success(res.data.msg, 1)
      setMustRender(mustRender + 1)
    } else {
      message.error(res.data.msg, 1)
    }
  }
  const delUserInGroup = async (userId) => {
    const res = await Axios.delete(`/admin/groupUser/${params.id}/${userId}`)
    if (res.data.code === 200) {
      message.success('删除成功', 1)
      setMustRender(mustRender => mustRender + 1)
    }
  }
  const showModal = () => {
    setIsModalVisible(true);
  };
  const handleOk = () => {
    setIsModalVisible(false);
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const showAttInfoModal = (item) => {
    setAttInfoItem(item)
    setAttInfoVisible(true)
  }
  //获取考勤组用户
  useEffect(function getGroupInfo() {
    Axios.get(`/admin/adminGroup/${params.id}`)
      .then(res => {
        res.data.code === 200 && setGroupInfo(res.data.data)
      })
  }, [params.id])
  //获取考勤组信息
  useEffect(function getAllUsersInGroup() {
    Axios.get(`/admin/getUserInfoListByGroup/${params.id}`)
      .then(res => {
        if (res.data.code === 200) {
          setUsers(() => [...res.data.data])
        } else {
          message.error('获取信息失败！', 1)
        }
      })
  }, [params.id, mustRender])
  //获取考勤组所有考勤记录
  useEffect(function getAllAttendances() {
    Axios.get(`/admin/getAttendancesByGroup/${params.id}`)
      .then(res => {
        if (res.data.code === 200) setAttdances(res.data.data)
      })
  }, [params.id, mustRender])

  return (
    <div className="att">

      <div className="att-box">

        <div className="att-left">
          <div className="att-left-top">
            <div className="group-title">
              {groupInfo.name}
              <Button type="primary" size="large" onClick={() => setAddAttvisible(true)}>新建考勤</Button>
            </div>
            <div className="feature-btn-group">
              <span className="add-user-btn" onClick={showModal}>添加成员</span>
            </div>
          </div>
          <div className="att-left-bottom">
            <List
              bordered
              dataSource={attdances}
              size="large"
              renderItem={item => (
                <List.Item onClick={() => showAttInfoModal(item)}>
                  <div style={{width: 220}}>{item.description}</div>
                  <div style={{width: 200}}>开始：{item.startTime}</div>
                  <div style={{width: 200}}>结束：{item.endTime}</div>
                  <div style={{width: 80}}>{item.status === 0 ? '已结束' : item.status === 1 ? '待考勤' : '正在考勤'}</div>
                </List.Item>
              )}
            />
          </div>
        </div>

        <div className="att-right">
          <p className="title">全部成员 <span>{users.length}人</span></p>
          <ul className="att-users-ul">
            {
              users.map(item => (
                <li key={item.email}>
                  <span>{item.name ? item.name : '未命名'}</span>
                  <span className="user-li-email">{item.email}</span>
                  <Popconfirm
                    title="是否要删除该用户?"
                    onConfirm={() => delUserInGroup(item.id)}
                    okText="是"
                    cancelText="否"
                  >
                    <img src={del} alt="加载失败"/>
                  </Popconfirm>
                </li>
              ))
            }
          </ul>
        </div>

      </div>

      <Modal title="添加成员"
             visible={isModalVisible}
             onOk={handleOk}
             onCancel={handleCancel}
             footer={null}
             style={{height: 500}}
      >
        <div className="mymodal-input">
          <Search placeholder="搜索用户" onSearch={onSearch} enterButton/>
        </div>
        <div className="mymodal-content">
          {
            searchUser ?
              searchUser.map(
                item => (
                  <div key={item.id} className="user-li">
                    <span>{item.name}</span>
                    <span>{item.email}</span>
                    <span className="add-btn" onClick={() => addUserToGroup(item.id)}>添加</span>
                  </div>
                )) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
          }
        </div>
      </Modal>
      <AddAttendanceModal visible={addAttVisible} setVisible={setAddAttvisible} id={params.id} mustState={mustRender}
                          mustRender={setMustRender}/>
      <AttendanceInfo visible={attInfoVisible} setVisible={setAttInfoVisible} item={attInfoItem} mustState={mustRender}
                      mustRender={setMustRender}/>
    </div>
  )
}

export default AttPage

function AddAttendanceModal(props) {
  const [desc, setDesc] = useState('考勤' + Math.floor(Math.random() * 1000))
  const [date, setDate] = useState('')
  const [startTime, setStartTime] = useState('')
  const [endTime, setEndTime] = useState('')

  const putNewAttendance = async () => {
    const _startTime = date + ' ' + startTime
    const _endTime = date + ' ' + endTime
    const url = `/admin/attendance/${props.id}/${desc}/${_startTime}/${_endTime}`
    const res = await Axios.post(url)
    if (res.data.code === 200) {
      message.success(res.data.msg, 1)
      props.mustRender(props.mustState + 1)
    } else {
      message.error(res.data.msg, 2)
    }
  }
  const onOk = () => {
    putNewAttendance()
    props.setVisible(false)
  }
  const onCancel = () => {
    props.setVisible(false)
  }
  const timeChange = (moment, timeString) => {
    setStartTime(timeString[0])
    setEndTime(timeString[1])
  }
  return (
    <Modal title="创建考勤"
           visible={props.visible}
           onOk={onOk}
           onCancel={onCancel}
           okText="创建"
           cancelText="取消"
           style={{height: 500}}
           className="add-new-att"
    >
      <DatePicker placeholder="选择日期" onChange={(m, dateString) => setDate(dateString)}/>
      <TimePicker.RangePicker placeholder={['开始时间', '结束时间']} onChange={timeChange}/>
      <TextArea rows={4}
                style={{resize: "none"}}
                placeholder={desc}
                value={desc}
                onChange={e => setDesc(e.target.value)}
      />
    </Modal>
  )
}

